import * as types from "../../mutation-types";
import api from "../../../api";

// * set user info
export const setUserInfoAction = (userInfo) => ({
	type: types.SET_USER_INFO,
	data: userInfo
});

// * set language
export const setLanguageAction = (language) => ({
	type: types.SET_LANGUAGE,
	data: language
});

// * set token
export const setTokenAction = (token) => ({
	type: types.SET_TOKEN,
	data: token
});

// * set theme
export const setThemeAction = (theme) => ({
	type: types.SET_PAGE_THEME,
	data: theme
});

// 以下测试异步

// * redux-thunk
export const getUserInfoActionThunk = () => {
	return async (dispatch) => {
		const res = await api.auth.getUserInfo();
		dispatch({
			type: types.SET_USER_INFO,
			data: (res.data) ?? {}
		});
	};
};

export const getTokenActionThunk = () => {
  return async (dispatch) => {
		const res = await api.auth.login();
		dispatch({
			type: types.SET_TOKEN,
			data: res.data && res.data.token ? res.data.token : ''
		});
	};
}

// * redux-promise《async/await》
export const getUserInfoAction = async () => {
	const res = await api.auth.getUserInfo();
	return {
		type: types.SET_USER_INFO,
		data: res.data ? res.data : {}
	};
};

// * redux-promise《.then/.catch》
export const getUserInfoActionPromise = async () => {
	return await (async (dispatch) => {
		const res = await api.auth.getUserInfo().catch(err => {
      console.log(err)
    });
		dispatch({
			type: types.SET_USER_INFO,
			data: (res?.data) ?? {}
		});
	});
};